﻿using System.Collections.Generic;

namespace FileTransformer
{
    public class DataSourceList
    {
        private readonly Dictionary<string, IDataSource> _sources = new Dictionary<string, IDataSource>();

        public event Logger OnLog;
        public event NewItemEvent OnNewItem;

        private void DoLog(string text, params object[] args)
        {
            if (OnLog != null)
                OnLog(string.Format(text, args));
        }

        public void Add(string name, IDataSource item)
        {
            var newName = GetNewName(name);
            _sources.Add(newName, item);

            if (OnNewItem != null)
                OnNewItem(newName, item);
        }

        public Dictionary<string, IDataSource>.Enumerator GetEnumerator()
        {
            return _sources.GetEnumerator();
        }

        private string GetNewName(string fileName)
        {
            var counter = 10;
            var extension = FileUtils.GetExtension(fileName) ?? "";
            var str2 = fileName.Remove(fileName.Length - extension.Length);
            var newName = str2 + extension;
            while (_sources.ContainsKey(newName))
            {
                newName = string.Format("{0}_{1}{2}", str2, counter, extension);
                counter++;
            }
            DoLog("GetNewName: result = <{0}>", newName);
            return newName;
        }

        public IDataSource GetSource(string fileName)
        {
            return _sources[fileName];
        }

        public void Remove(string name)
        {
            _sources.Remove(name);
        }
    }
}